package proyectosdcliente;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Hashtable;

public class Client extends Thread{

    private DatagramSocket _socket;
    private Hashtable servs;
    private javax.swing.JTextArea content;
    private int timerPort;
    private boolean stopTimer;
    private boolean stop;

    public Client(int puerto, javax.swing.JTextArea content, Hashtable servs, Integer timerPort) {
        this.content = content;
        this.stopTimer = false;
        this.servs = servs;
        try{
            _socket = new DatagramSocket(puerto);
        } catch(Exception e){
            e.printStackTrace();
        }
        this.timerPort = timerPort;
        stop = false;
    }

    public void setStopTimer(){
        this.stopTimer = true;
    }

    @Override
    public void run(){
        do {
            try{
                DatagramPacket packet = new DatagramPacket(new byte[255],255);
                _socket.receive(packet);
                if(stopTimer)
                    stopTimer();
                byte[] data = packet.getData();
                String msg = new String(data);
                msg = msg.trim();
                String[] datos = msg.split(";");
                int op = Integer.parseInt(datos[0]);
                String[] registro = datos[1].split(":");
                String id = registro[0];
                switch(op){
                    case 1:
                        // ACK de inserción
                        Integer idServ = Integer.parseInt(id);
                        Integer servPort = Integer.parseInt(registro[1]);
                        if(!servs.containsKey(idServ))
                            servs.put(idServ, servPort);
                        break;
                    case 2:
                        // Respuesta de recuperación de datos
                        content.setText(datos[1]);
                        break;
                    case 3:
                        // Timeout
                        ProyectoSDClienteView.obs_cliente.add("Timeout: Operación cancelada.");
                        break;
                }
            } catch(Exception e){
                e.printStackTrace();
            }
        } while(!stop);
    }

    public void killServer(){
        stop = true;
    }

    private void stopTimer() {
        try {
            _socket.connect(InetAddress.getLocalHost(), timerPort);
            _socket.send(new DatagramPacket("1".getBytes(), 1));
            _socket.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        stopTimer = false;
    }
}
